package com.example.gateway.apiapigateway.filter;

import api.apiservice.apiopenplat.service.IApiInfoService;
import com.example.gateway.apiapigateway.entity.ApiInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {


    @DubboReference
    private IApiInfoService apiInfoService;


    @Override
    public int getOrder() {
        return -1;
    }

    /**
     *
     * API在线调用前校验
     *
     * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ApiInfo existApi = apiInfoService.isExistApi(3L);
        if(existApi == null){
            return Mono.empty();
        }
        if (existApi.getAFreeCount()<0) {
            return Mono.error(new RuntimeException("API免费次数已消耗完毕，请重新购买API调用次数！"));
        }
        /**
         * TODO
         * 判断用户是否黑名单
         * */

        System.out.println(existApi);
        return chain.filter(exchange);
    }
}

